package com.hospital.hospitalsystem.modules.base.biz;

import com.hospital.hospitalsystem.config.MinioConfig;
import com.hospital.hospitalsystem.modules.base.dto.DeleteReq;
import com.hospital.hospitalsystem.modules.base.dto.UploadRsp;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

/**
 * @author qiancheng@cqxyy.net
 * @date 2022/11/7
 */
@Service
public class UploadBiz {
    @Autowired
    private MinioConfig minioConfig;

    /**
     * 上传文件
     * @param file
     * @return
     */
    public UploadRsp upload(MultipartFile file,String bucketName) {
        UploadRsp result = new UploadRsp();
        String fileName = System.currentTimeMillis() + "";
        String fileSuffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        minioConfig.makeBucket(bucketName);
        String url = minioConfig.putObject(bucketName,file,fileName);
        result.setUrl(url);
        result.setFileName(fileName + fileSuffix);
        return result;
    }

    /**
     * 删除图片
     * @param deleteReq
     */
    public void delete(DeleteReq deleteReq) {
        if (CollectionUtils.isNotEmpty(deleteReq.getObjectName())) {
            deleteReq.getObjectName().forEach(objectName -> {
                boolean flag = minioConfig.removeObject(deleteReq.getBucketName(),objectName);
                if (!flag) {
                    throw new RuntimeException("删除文件失败");
                }
            });
        }
    }
}
